<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目编号" prop="pjNo">
        <el-input
          v-model="queryParams.pjNo"
          placeholder="请输入项目编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目名称" prop="pjName">
        <el-input
          v-model="queryParams.pjName"
          placeholder="请输入项目名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目经理" prop="pjManager">
        <el-input
          v-model="queryParams.pjManager"
          placeholder="请输入项目经理"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目销售" prop="pjSaler">
        <el-input
          v-model="queryParams.pjSaler"
          placeholder="请输入项目销售"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目状态" prop="pjState">
        <el-select v-model="queryParams.pjState" placeholder="请选择项目状态" clearable>
          <el-option
            v-for="dict in pjStateOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="开始时间">
        <el-date-picker
          v-model="pjStartDateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['project:project:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['project:project:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['project:project:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['project:project:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="projectList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="项目id" align="center" prop="pjId" /> -->
      <el-table-column label="项目编号" align="center" prop="pjNo" />
      <el-table-column label="项目名称" align="center" prop="pjName" />
      <el-table-column label="项目区域" align="center" prop="pjDivison" />
      <el-table-column label="项目经理" align="center" prop="pjManagerName" />
      <el-table-column label="项目销售" align="center" prop="pjSaler" />
      <el-table-column label="项目金额" align="center" prop="pjAmout" />
      <el-table-column label="项目状态" align="center" prop="pjState">
        <template slot-scope="scope">
          <dict-tag :options="pjStateOptions" :value="scope.row.pjState"/>
        </template>
      </el-table-column>
      <el-table-column label="项目开始时间" align="center" prop="pjStartDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.pjStartDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="项目预计结束时间" align="center" prop="pjEtimatedCompletionDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.pjEtimatedCompletionDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['project:project:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['project:project:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="项目编号" prop="pjNo">
          <el-input v-model="form.pjNo" placeholder="请输入项目编号" />
        </el-form-item>
        <el-form-item label="项目名称" prop="pjName">
          <el-input v-model="form.pjName" placeholder="请输入项目名称" />
        </el-form-item>
        <el-form-item label="项目区域" prop="pjDivison">
          <el-input v-model="form.pjDivison" placeholder="请输入项目区域" />
        </el-form-item>
        <el-form-item label="项目经理" prop="pjManager">
          <el-input
            v-model="form.pjManagerName"
            placeholder="请选择项目经理"
            readonly
          >
            <el-button slot="append" icon="el-icon-search" @click="handleUserSelect('pjManager')"></el-button>
          </el-input>
          <!-- 使用样式完全隐藏 -->
          <div style="display: none;">
            <el-input v-model="form.pjManager" />
          </div>
        </el-form-item>
        <el-form-item label="项目销售" prop="pjSaler">
          <el-input v-model="form.pjSaler" placeholder="请输入项目销售" />
        </el-form-item>
        <el-form-item label="项目金额" prop="pjAmout">
          <el-input v-model="form.pjAmout" placeholder="请输入项目金额" />
        </el-form-item>
        <el-form-item label="项目状态" prop="pjState">
          <el-select v-model="form.pjState" placeholder="请选择项目状态">
            <el-option
              v-for="dict in pjStateOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="项目开始时间" prop="pjStartDate">
          <el-date-picker clearable
                          v-model="form.pjStartDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择项目开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="预计结束时间" prop="pjEtimatedCompletionDate">
          <el-date-picker clearable
                          v-model="form.pjEtimatedCompletionDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择项目预计结束时间">
          </el-date-picker>
        </el-form-item>
        <!-- <el-form-item label="实际结束时间" prop="pjCompletionDate">
          <el-date-picker clearable
            v-model="form.pjCompletionDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择项目时间结束时间">
          </el-date-picker>
        </el-form-item> -->
        <el-form-item label="项目简介" prop="pjDesc">
          <el-input v-model="form.pjDesc" type="textarea" placeholder="请输入项目简介" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户选择对话框 -->
    <el-dialog title="选择用户" :visible.sync="userSelectVisible" width="800px" append-to-body>
      <user-select @userSelected="handleUserSelected" />
    </el-dialog>
  </div>
</template>

<script>
import { listProject, getProject, delProject, addProject, updateProject } from "@/api/project/project"
// 导入用户选择组件
import UserSelect from "@/components/UserSelect"

export default {
  name: "Projectinfo",
  components: {
    UserSelect
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 项目信息表格数据
      projectList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 用户选择对话框显示状态
      userSelectVisible: false,
      // 当前选择的字段
      currentField: "",
      // 日期范围
      pjStartDateRange: [],
      // 项目状态字典
      pjStateOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        pjNo: null,
        pjName: null,
        pjManager: null,
        pjSaler: null,
        pjState: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        pjNo: [
          { required: true, message: "项目编号不能为空", trigger: "blur" }
        ],
        pjName: [
          { required: true, message: "项目名称不能为空", trigger: "blur" }
        ],
        pjAmout: [
          { required: true, message: "项目金额不能为空", trigger: "blur" }
        ],
        pjState: [
          { required: true, message: "项目状态不能为空", trigger: "change" }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getDicts("pj_project_state").then(response => {
      this.pjStateOptions = response.data
    })
  },
  methods: {
    /** 查询项目信息列表 */
    getList() {
      this.loading = true
      const queryData = {
        ...this.queryParams,
        params: {
          ...this.queryParams.params
        }
      };
      // 修改参数名与后端匹配
      if (this.pjStartDateRange && this.pjStartDateRange.length === 2) {
        queryData.params.beginPjStartDate = this.pjStartDateRange[0];
        queryData.params.endPjStartDate = this.pjStartDateRange[1];
      }


      listProject(queryData).then(response => {
        this.projectList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        pjId: null,
        pjNo: null,
        pjName: null,
        pjDivison: null,
        pjManager: null, // 存储用户ID
        pjManagerName: null, // 存储显示名称
        pjSaler: null,
        pjAmout: null,
        pjState: null,
        pjStartDate: null,
        pjEtimatedCompletionDate: null,
        pjCompletionDate: null,
        pjDesc: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.pjStartDateRange = []
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.pjId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加项目信息"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const pjId = row.pjId || this.ids
      getProject(pjId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改项目信息"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.pjId != null) {
            updateProject(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addProject(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const pjIds = row.pjId || this.ids
      this.$modal.confirm('是否确认删除项目信息编号为"' + pjIds + '"的数据项？').then(function() {
        return delProject(pjIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('project/project/export', {
        ...this.queryParams
      }, `project_${new Date().getTime()}.xlsx`)
    },
    /** 打开用户选择对话框 */
    handleUserSelect(field) {
      this.currentField = field
      this.userSelectVisible = true
    },
    /** 处理用户选择结果 */
    handleUserSelected(user) {
      this.userSelectVisible = false

      if (user && this.currentField) {
        // 根据当前字段设置对应的ID和显示名称
        if (this.currentField === 'pjManager') {
          this.form.pjManager = user.userId        // 存储用户ID到数据库
          this.form.pjManagerName = user.nickName ? `${user.nickName}(${user.userName})` : user.userName // 显示给用户看的名称
        }
        // 可以扩展其他字段，比如项目销售
        // else if (this.currentField === 'pjSaler') {
        //   this.form.pjSalerId = user.userId
        //   this.form.pjSalerName = user.displayName
        // }
      }
      this.currentField = ""
    }
  }
}
</script>
